package com.atguigu.tingshu.live.service.impl;

import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.live.mapper.LiveRoomMapper;
import com.atguigu.tingshu.live.service.LiveRoomService;
import com.atguigu.tingshu.live.utils.LiveAdressUtil;
import com.atguigu.tingshu.model.live.LiveRoom;
import com.atguigu.tingshu.vo.live.LiveRoomVo;
import com.atguigu.tingshu.vo.live.TencentLiveAddressVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class LiveRoomServiceImpl extends ServiceImpl<LiveRoomMapper, LiveRoom> implements LiveRoomService {

	@Autowired
	private LiveRoomMapper liveRoomMapper;
	@Resource
	private LiveAdressUtil liveAdressUtil;

	@Override
	public LiveRoom getCurrentLive() {
		return liveRoomMapper.selectOne(new LambdaQueryWrapper<LiveRoom>()
				.eq(LiveRoom::getUserId, AuthContextHolder.getUserId())
				.gt(LiveRoom::getExpireTime,new Date()));
	}

	@Override
	public LiveRoom saveLiveRoom(LiveRoomVo liveRoomVo) {
		//自己未过期的直播间
		LiveRoom liveRoom = liveRoomMapper.selectOne(new LambdaQueryWrapper<LiveRoom>()
				.eq(LiveRoom::getUserId, AuthContextHolder.getUserId())
				.gt(LiveRoom::getExpireTime,new Date()));
		if (liveRoom!=null){
			return liveRoom;
		}
		liveRoom = new LiveRoom();
		BeanUtils.copyProperties(liveRoomVo,liveRoom);
		liveRoom.setUserId(AuthContextHolder.getUserId());
		liveRoom.setStatus("1");
		liveRoom.setAppName("谷粒随享直播功能");
		String streamName = "atguigu" + IdWorker.getIdStr();
		liveRoom.setStreamName(streamName);
		Date expireTime = liveRoom.getExpireTime();
		// 获取推拉流地址
		TencentLiveAddressVo tencentLiveAddresses = liveAdressUtil.getTencentLiveAddress(expireTime.getTime() / 1000, streamName);
		liveRoom.setPushUrl(tencentLiveAddresses.getPushWebRtcUrl());
		liveRoom.setPlayUrl(tencentLiveAddresses.getPullWebRtcUrl());
		this.save(liveRoom);
		return liveRoom;
	}

	@Override
	public List<LiveRoom> findLiveList() {
		return liveRoomMapper.selectList(new LambdaQueryWrapper<LiveRoom>()
				.gt(LiveRoom::getExpireTime,new Date()));
	}
}
